package com.dolphin.artifact.service.impl;


import com.dolphin.artifact.common.redis.ShareRedisManage;
import com.dolphin.artifact.common.utils.JWTUtil;
import com.dolphin.artifact.common.utils.UserDTO;
import com.dolphin.artifact.service.UserInfoService;
import com.dolphin.artifact.common.annotation.TargetDataSource;
import com.dolphin.artifact.common.model.ResultModel;
import com.dolphin.artifact.dao.UserInfoMapper;
import com.dolphin.artifact.dao.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.transform.Result;
import java.util.Optional;

/**
 * Created by hhwf on 2017/10/15.
 */
@Service("userInfoService")
public class UserInfoServiceImpl  implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private ShareRedisManage shareRedisManage;




    @Transactional(rollbackFor = Exception.class)
    @TargetDataSource(dataSource = TargetDataSource.DATA_SOURCE_WRITE)
    @Override
    public ResultModel getUserInfoById(Long id){
        ResultModel resultModel = new ResultModel();
        resultModel.setData(userInfoMapper.selectByPrimaryKey(id));
        return resultModel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @TargetDataSource(dataSource = TargetDataSource.DATA_SOURCE_WRITE)
    public ResultModel login(String userName , String password ) {
        ResultModel result = new ResultModel();
        UserInfo userInfo = userInfoMapper.selectByUserName(userName,password);
        if (null == userInfo){
            result.setCode(ResultModel.ERROR);
            result.setMsg("用户名密码错误");
            return result;
        }
        UserDTO userDTO = new UserDTO();
        userDTO.setUserid(userInfo.getId());
        String token = JWTUtil.sign(userDTO);
        result.setData(token);
        return result;
    }


}
